package com.yzkj.cpjxc.business.controller;

import com.yzkj.cpjxc.business.domain.*;
import com.yzkj.cpjxc.business.framework.common.*;
import com.yzkj.cpjxc.business.framework.utils.CollectionHelp;
import com.yzkj.cpjxc.business.framework.utils.StringHelp;
import com.yzkj.cpjxc.business.service.SysDeptService;
import com.yzkj.cpjxc.business.service.SysRoleService;
import com.yzkj.cpjxc.business.service.SysUserService;
import com.yzkj.cpjxc.business.system.interceptor.DoLog;
import com.yzkj.cpjxc.business.system.interceptor.Permission;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * 系统用户控制器
 */
@Controller
@RequestMapping("/sysUser")
public class SysUserController extends BaseController {

	@Autowired
	private SysUserService sysUserService;

	@Autowired
	private SysRoleService sysRoleService;

	@Autowired
	private SysDeptService sysDeptService;

	@RequestMapping("/list")
	@DoLog(cnContent = "去到系统用户列表信息", value = false)
	@Permission(name = "sysUser.view")
	public ModelAndView list(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//1、组装数据，启用状态下拉框
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("statusMap", ConstantParam.statusMap);
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("sysMgr/securityMgr/sysUser/list").addAllObjects(modelMap);
	}

	@RequestMapping("/ajaxPage")
	@DoLog(cnContent = "系统用户列表ajax分页", value = false)
	@Permission(name = "sysUser.view")
	public String ajaxPage(HttpServletRequest request, HttpServletResponse response, SysUserQueryVo queryVo) throws Exception {
		try {
			Pager<SysUser> p = new Pager<SysUser>();
			p.setCurrentPage(this.getCurrentPage(request));
			
			SysUser currentUser = (SysUser) request.getSession().getAttribute(Constants.CURRENT_USER);
			if(Constants.ADMIN.equals(currentUser.getUsername())){
				queryVo.setNotAdmin(false);
			}else{
				queryVo.setNotAdmin(true);
				//不列出当前用户个人账户信息(除了超级管理员admin自己外)
				queryVo.setCurrUserName(currentUser.getUsername());
			}
			
			
			//3.1、初始化参数。用于拼接数据。
			Pager<SysUser> pager = sysUserService.search(p, queryVo);
			this.genPageJson(response, pager);
			return null;
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}

	}

	@RequestMapping("/toAdd")
	@DoLog(cnContent = "去到添加系统用户页面", value = false)
	@Permission(name = "sysUser.add")
	public ModelAndView toAdd(HttpServletRequest request, HttpServletResponse response) throws Exception {
		//1、组装数据，状态下拉框，删除状态，前台参数
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("statusMap", ConstantParam.statusMap);
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("sysMgr/securityMgr/sysUser/add").addAllObjects(modelMap);
	}

	@RequestMapping("/add")
	@DoLog(cnContent = "添加系统用户", operationAction = "C")
	@Permission(name = "sysUser.add")
	public void add(HttpServletRequest request, HttpServletResponse response, SysUserQueryVo sysUser) throws Exception {
		BusinessMap bm = new BusinessMap();
		try {
			
			//过滤指定非法字符
			StringHelp.replaceFilteringChars(SysUser.class, sysUser);
			
			//1、获取当前登录用户信息
			bm = sysUserService.create(sysUser);
			this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
		} catch (Exception e) {
			this.logException(e);
			this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/toEdit")
	@DoLog(cnContent = "去到编辑系统用户页面", value = false)
	@Permission(name = "sysUser.edit")
	public ModelAndView toEdit(HttpServletRequest request, HttpServletResponse response, SysUser sysUser) throws Exception {
		SysUser result = sysUserService.getById(sysUser.getUserId());
		//获取修改用户的部门信息，
		String deptName = "";
		String deptId = "";
		for (Object obj : result.getSysDepts()) {
			SysDept dept = (SysDept) obj;
			deptName = dept.getDeptCnName() + "," + deptName;
			deptId = dept.getDeptId() + "," + deptId;
		}
		//3、拷贝数据，设置部门id，和部门名称
		SysUserShowVo showVo = new SysUserShowVo();
		BeanUtils.copyProperties(result, showVo, new String[] {
				"sysRoles", "sysDepts" , "sysAuthoritys"//排除这些属性不拷贝,防止出现死循环
		});
		showVo.setDeptId(deptId);
		showVo.setDeptName(deptName);
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("statusMap", ConstantParam.statusMap);
		modelMap.put("sysUser", showVo);
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("sysMgr/securityMgr/sysUser/edit").addAllObjects(modelMap);
	}

	@RequestMapping("/edit")
	@DoLog(cnContent = "编辑系统用户", operationAction = "C")
	@Permission(name = "sysUser.edit")
	public void edit(HttpServletRequest request, HttpServletResponse response, SysUserQueryVo sysUser) throws Exception {
		try {
			
			//过滤指定非法字符
			StringHelp.replaceFilteringChars(SysUser.class, sysUser);
			
			//1、获取当前登录用户信息
			BusinessMap bm = sysUserService.edit(sysUser);
			this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
		} catch (Exception e) {
			this.logException(e);
			this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	@RequestMapping("/view")
	@DoLog(cnContent = "查看系统用户信息", value = false)
	@Permission(name = "sysUser.view")
	public ModelAndView view(HttpServletRequest request, HttpServletResponse response, SysUser sysUser) throws Exception {
		SysUser su = sysUserService.getById(sysUser.getUserId());

		String roleNames = "";
		List<SysRole> srList = su.getSysRoles();

		if (CollectionHelp.isNotBank(srList)) {
			for (SysRole sr : srList) {
				roleNames = roleNames + "," + sr.getRoleName();
			}
			if (roleNames.length() > 0) {
				roleNames = roleNames.substring(0, roleNames.length() - 1);
			}
		}
		//5、拷贝数据，设置角色中文名称，部门中文名称
		
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("sysUser", su);
		modelMap.put("roleNames", roleNames);
		return new ModelAndView("sysMgr/securityMgr/sysUser/view").addAllObjects(modelMap);
	}

	@RequestMapping("/delete")
	@DoLog(cnContent = "删除系统用户信息", operationAction = "D")
	@Permission(name = "sysUser.delete")
	public void delete(HttpServletRequest request, HttpServletResponse response, SysUser sysUser) throws Exception {
		try {
			//1、删除用户，根据flag，返回message
			BusinessMap bm = sysUserService.delete(sysUser.getUserId());
			this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
		} catch (Exception e) {
			this.logException(e);
			this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	// ====================================================================给用户设置角色 开始==============================================================================

	@RequestMapping("/toSetRole")
	@DoLog(cnContent = "去到用户设置角色页面", value = false)
	@Permission(name = "sysUser.setRole")
	public ModelAndView toSetRole(HttpServletRequest request, HttpServletResponse response, SysUserQueryVo queryVo) throws Exception {
		//1、获取用户信息。
		SysUser su = sysUserService.getById(queryVo.getUserId());
		//2、遍历角色拼接成串。
		List<SysRole> srList = su.getSysRoles();
		String roleIds = "";
		if (CollectionHelp.isNotBank(srList)) {
			for (SysRole sr : srList) {
				roleIds = sr.getRoleId() + "," + roleIds;
			}
		}
		//3、拷贝数据，设置角色id
		queryVo.setRoleIds(roleIds);
		return new ModelAndView("sysMgr/securityMgr/sysUser/setRole").addObject("sysUser", su).addObject("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
	}

	@RequestMapping("/setRole")
	@DoLog(cnContent = "设置用户角色", operationAction = "SETROLE")
	@Permission(name = "sysUser.setRole")
	public void setRole(HttpServletRequest request, HttpServletResponse response, SysUserQueryVo queryVo) throws Exception {
		try {
			
			//不允许设置超级管理员admin的角色信息
			SysUser su = sysUserService.getById(queryVo.getUserId());
			if(su != null && Constants.ADMIN.equals(su.getUsername())){
				this.ajax(response, "不允许设置超级管理员admin的角色信息!");
				return;
			}
			
			//1、保存用户角色信息
			BusinessMap bm = sysUserService.setRole(queryVo);
			this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
		} catch (Exception e) {
			this.logException(e);
			this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}

	// ====================================================================给用户设置角色 结束==============================================================================

	@RequestMapping("/relevanceRole")
	@DoLog(cnContent = "查看用户关联的角色列表", value = false)
	@Permission(name = "sysUser.view")
	public ModelAndView relevanceRole(HttpServletRequest request, HttpServletResponse response, SysUserQueryVo queryVo) throws Exception {
		//1、根据userId获取用户信息
		SysUser result = sysUserService.getById(queryVo.getUserId());
		//3、遍历用户角色
		String roleNames = "";
		List<SysRole> srList = result.getSysRoles();
		if (CollectionHelp.isNotBank(srList)) {
			for (SysRole sr : srList) {
				roleNames = sr.getRoleName() + "," + roleNames;
			}
		}
		//4、删除角色字符串最后的标点
		if (roleNames.length() > 0) {
			roleNames = roleNames.substring(0, roleNames.length() - 1);
		}
		HashMap<String, Object> modelMap = new LinkedHashMap<String, Object>();
		modelMap.put("sysUser", result);
		modelMap.put("roleNames", roleNames);
		modelMap.put("csrfToken", CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("sysMgr/securityMgr/sysUser/relevanceRole").addAllObjects(modelMap);
	}

	@RequestMapping("/ajaxPageByDeptId")
	@DoLog(cnContent = "查看部门下的用户列表", value = false)
	public String ajaxPageByDeptId(HttpServletRequest request, HttpServletResponse response, SysUserQueryVo queryVo) throws Exception {
		try {
			Pager<SysUser> p = new Pager<SysUser>();
			p.setCurrentPage(this.getCurrentPage(request));
			//3.1、初始化参数。用于拼接数据。
			Pager<SysUser> pager = sysUserService.getUserByDeptId(p, queryVo);
			this.genPageJson(response, pager);
			return null;
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}

	}

	/**
	 * @description: 异步验证用户名是否存在
	 */
	@RequestMapping("/isExistsUserName")
	public void isExistsUserName(HttpServletRequest request, HttpServletResponse response, String userName) throws Exception {
		boolean isExistsUserName = sysUserService.isExistsUserName(userName);
		if (isExistsUserName) {
			this.ajax(response, "true");
		} else {
			this.ajax(response, "false");
		}
	}

	/**
	 * @description: 异步验证身份证是否存在
	 */
	@RequestMapping("/isExistsIdCardNo")
	public void isExistsIdCardNo(HttpServletRequest request, HttpServletResponse response, String idCardNo) throws Exception {
		boolean isExistsIdCardNo = sysUserService.isExistsIdCardNo(idCardNo);
		if (isExistsIdCardNo) {
			this.ajax(response, "true");
		} else {
			this.ajax(response, "false");
		}
	}

	@RequestMapping("/relevanceDept")
	@DoLog(cnContent = "查看用户关联的部门列表", value = false)
	public ModelAndView relevanceDept(HttpServletRequest request, HttpServletResponse response, SysUserQueryVo queryVo) throws Exception {
		//1、根据userId获取用户信息
		SysUser sysUser = sysUserService.getById(queryVo.getUserId());
		//2、遍历用户部门
		//List<SysDeptShowVo> sysDeptList = sysDeptService.getDeptByUserId(queryVo.getUserId());
		List<SysDept> sysDeptList = sysUser.getSysDepts();
		String deptName = "";
		//3、组装数据
		if (CollectionHelp.isNotBank(sysDeptList)) {
			for (SysDept sysDept : sysDeptList) {
				deptName = sysDept.getDeptCnName() + "," + deptName;
			}
		}
		SysUserShowVo showVo = new SysUserShowVo();
		BeanUtils.copyProperties(sysUser, showVo, new String[] {
				"sysRoles", "sysDepts" , "sysAuthoritys"//排除这些属性不拷贝,防止出现死循环
		});
		//4、删除部门后面的小树点
		if (deptName.length() > 0) {
			deptName = deptName.substring(0, deptName.length() - 1);
		}
		showVo.setDeptName(deptName);
		return new ModelAndView("sysMgr/securityMgr/sysUser/relevanceDept").addObject("sysUserShowVo", showVo).addObject("csrfToken",
				CSRFTokenManager.getTokenForSession(request.getSession()));
	}
	
	@RequestMapping("/ajaxPageByRoleId")
	@DoLog(cnContent = "查看角色关联的用户列表", value = false)
	public String ajaxPageByRoleId(HttpServletRequest request, HttpServletResponse response, SysUserQueryVo queryVo) throws Exception {
		try {
			Pager<SysUser> p = new Pager<SysUser>();
			p.setCurrentPage(this.getCurrentPage(request));
			//3.1、初始化参数。用于拼接数据。
			Pager<SysUser> pager = sysUserService.ajaxPageByRoleId(p, queryVo);
			this.genPageJson(response, pager);
			return null;
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}

	}
	
	/**
	 * 去到修改密码页面
	 */
	@RequestMapping("/toEditPassword") 
	@DoLog(cnContent="去到修改密码页面") 
	@Permission(name="sysUser.editPassword")
	public ModelAndView toEdit(HttpServletRequest request, HttpServletResponse response, SysUserQueryVo vo) throws Exception {
		HashMap<String, Object> modelMap=new LinkedHashMap<String, Object>();
		modelMap.put("csrfToken",  CSRFTokenManager.getTokenForSession(request.getSession()));
		return new ModelAndView("sysMgr/securityMgr/sysUser/editPassword").addAllObjects(modelMap);
	}
	
	/**
	 * 用户修改秘密
	 */
	@RequestMapping("/editPassword") 
	@DoLog(cnContent="用户修改秘密", operationAction = "U") 
	@Permission(name="sysUser.editPassword")
	public String edit(HttpServletRequest request, HttpServletResponse response, SysUserEditPassVo vo) throws Exception {
		try {
			
			//获取当前登录用户
			SysUser currentUser = (SysUser) request.getSession().getAttribute(Constants.CURRENT_USER);
			
			vo.setUserId(currentUser.getUserId());
			vo.setCurrentPassword(currentUser.getPassword());
			
			BusinessMap bm = sysUserService.changePass(vo);
			return this.ajax(response, bm.getIsSucc() ? Constants.SUCCESS : bm.getAlertMesg());
		} catch (Exception e) {
			this.logException(e);
			return this.ajax(response, "系统出现异常: [" + e.getMessage() + "] 请与管理员联系！");
		}
	}
}
